﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LearningBubbles
{
    class BubbleObservable : IObservable<Player>
    {
        class Unsubscriber : IDisposable
        {

            private List<IObserver<Player>> _observers;
            private IObserver<Player> _observer;

            public Unsubscriber(List<IObserver<Player>> observers, IObserver<Player> observer)
            {
                this._observers = observers;
                this._observer = observer;
            }

            public void Dispose()
            {
                if (_observer != null && _observers.Contains(_observer))
                    _observers.Remove(_observer);            }
        }

        private List<IObserver<Player>> observers;

        public BubbleObservable()
        {
            observers = new List<IObserver<Player>>();
        }

        public IDisposable Subscribe(IObserver<Player> observer)
        {
            if (!observers.Contains(observer))
                observers.Add(observer);
            return new Unsubscriber(observers, observer);
        }

        public void UpdateCollectedElements(Player player)
        {
            foreach (var observer in observers)
            {
                if (player == null)
                    observer.OnError(new Exception("no player"));
                else observer.OnNext(player);
            }
        }
        public void EndTransmission()
        {
            foreach (var observer in observers)            {
                if (observers.Contains(observer))
                    observer.OnCompleted();
            }
            observers.Clear();
        }
    }
}